<template>
  <div>
    <h1>IndexedDB 数据加载</h1>
    <div class="button-group">
      <button @click="loadMyStoreData">加载MyStore数据</button>
      <button @click="loadCheckStoreData">加载CheckStore数据</button>
    </div>
    <div v-if="loading">加载中...</div>
    <div v-else>
      <h3 v-if="currentStore">{{ currentStore }} 数据：</h3>
      <pre>{{ jsonData }}</pre>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const DB_NAME = 'MyDatabase'
const STORE_NAMES = {
  MY_STORE: 'MyStore',
  CHECK_STORE: 'CheckStore'
}
const jsonData = ref(null)
const loading = ref(false)
const currentStore = ref(null)

const loadTableData = (storeName) => {
  loading.value = true
  jsonData.value = null
  currentStore.value = storeName
  
  const request = indexedDB.open(DB_NAME)

  request.onerror = (event) => {
    console.error('数据库打开失败:', event)
    loading.value = false
  }

  request.onsuccess = (event) => {
    const db = event.target.result
    const transaction = db.transaction(storeName, 'readonly')
    const store = transaction.objectStore(storeName)
    const getAllRequest = store.getAll()

    getAllRequest.onerror = (event) => {
      console.error('数据加载失败:', event)
      loading.value = false
    }

    getAllRequest.onsuccess = (event) => {
      jsonData.value = JSON.stringify(event.target.result, null, 2)
      loading.value = false
      db.close()
    }
  }
}

const loadMyStoreData = () => loadTableData(STORE_NAMES.MY_STORE)
const loadCheckStoreData = () => loadTableData(STORE_NAMES.CHECK_STORE)
</script>

<style scoped>
.button-group {
  margin-bottom: 15px;
}
.button-group button {
  margin-right: 10px;
}
pre {
  background: #f4f4f4;
  padding: 10px;
  border-radius: 5px;
  margin-top: 20px;
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>